package com.huli.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huli.domain.OrderInfo;
import com.huli.domain.OrderMaterial;
import com.huli.domain.SysMaterial;
import com.huli.domain.vo.OrderDetailVO;
import com.huli.domain.vo.OrderVerifyVO;
import com.huli.domain.vo.OrderVerifyResultVO;
import com.huli.domain.vo.ServiceCompleteVO;
import com.huli.mapper.OrderInfoMapper;
import com.huli.mapper.OrderMaterialMapper;
import com.huli.service.OrderInfoService;
import com.huli.util.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* @author 张庆阳
* @description 针对表【order_info(订单信息表)】的数据库操作Service实现
* @createDate 2025-03-17 11:52:08
*/
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo>
    implements OrderInfoService {
@Autowired
private OrderInfoMapper orderInfoMapper;
@Autowired
private OrderMaterialMapper orderMaterialMapper;

//查询完成的订单
    @Override
    public Integer updateOrderStatusByYes() {
       int statusByYes= orderInfoMapper.selectByStatus(3);
        System.out.println(statusByYes);
       return statusByYes;
    }
//查询为派单的订单
    @Override
    public int updateOrderStatusByNo() {
        int statusByNo = orderInfoMapper.selectByStatus(0);
        return statusByNo;
    }

    @Override
    public int updateOrderStatusByNotOk() {

        //查询待服务的订单
      int count1 = orderInfoMapper.selectByStatus(1);
      //查询服务中的订单
      int count2 = orderInfoMapper.selectByStatus(2);
      //完成未完成的订单相加
      int totalCount=count1+count2;
      if (totalCount>0){
          return totalCount;
      }else{
          return 0;
      }
  }
    //派单功能实现
    @Override
    public int updateOrderToGo(Integer nurseId,Integer id,@Param("messages") String messages) {
        int updateByGo = orderInfoMapper.upodateByGo(nurseId,id,messages);
       return updateByGo;
    }
    //订单的派单功能
    @Override
    public Result show(Integer orderId) {
        List<SysMaterial> show = orderInfoMapper.show(orderId);
        return new Result(200,"查询成功",show);
    }

    @Override
    public Result getcase(Integer id) {
      String caseImage =  orderInfoMapper.findCase(id);
      return new Result(200,"查询成功",caseImage);
    }
    //查询订单明细

    @Override
    public List<OrderDetailVO> findByOrderNo(OrderDetailVO orderDetailVO) {
        List<OrderDetailVO> orderInfoList = orderInfoMapper.findByOrderNo(orderDetailVO);
        return orderInfoList;
    }

    @Override
    public List<OrderDetailVO> getOrderDetail(OrderDetailVO orderDetailVO) {
        return orderInfoMapper.getOrderDetail(orderDetailVO);

    }

    @Override
    @Transactional
    public Result verifyAndStartService(OrderVerifyVO verifyVO) {
        // 打印请求参数
        System.out.println("验证请求参数: orderNo=" + verifyVO.getOrderNo()
            + ", verifyCode=" + verifyVO.getVerifyCode()
            + ", amount=" + verifyVO.getAmount());

        // 1. 获取订单信息
        OrderVerifyResultVO orderInfo = orderInfoMapper.verifyOrderCode(verifyVO.getOrderNo());
        if (orderInfo == null) {
            System.out.println("未找到订单信息，订单号: " + verifyVO.getOrderNo());
            return new Result(400, "订单不存在", null);
        }
        System.out.println("查询到的订单信息: orderAmount=" + orderInfo.getOrderAmount()
            + ", verifyCode=" + orderInfo.getVerifyCode()
            + ", orderStatus=" + orderInfo.getOrderStatus());

        // 2. 检查订单状态
        if (orderInfo.getOrderStatus() != 1) { // 1表示待服务状态
            return new Result(400, "订单状态不正确，只有待服务的订单才能开始服务", null);
        }

        // 3. 验证验证码
        System.out.println("验证码比对: 输入的验证码=[" + verifyVO.getVerifyCode()
            + "], 数据库中的验证码=[" + orderInfo.getVerifyCode() + "]");
        if (!Objects.equals(verifyVO.getVerifyCode(), orderInfo.getVerifyCode())) {
            return new Result(400, "验证码错误", null);
        }

        // 4. 更新订单状态为服务中
        int updated = orderInfoMapper.updateOrderStatusToServing(verifyVO.getOrderNo());
        System.out.println("更新订单状态结果: " + updated);
        if (updated > 0) {
            return new Result(200, "验证通过，服务开始", null);
        } else {
            return new Result(500, "更新订单状态失败", null);
        }
    }

    @Override
    @Transactional
    public Result completeService(ServiceCompleteVO completeVO,@RequestParam("messages") String messages) {
        // 打印请求参数
        System.out.println("收到服务完成请求，参数：");
        System.out.println("订单号：" + completeVO.getOrderNo());
        System.out.println("签到时间：" + completeVO.getSignInTime());
        System.out.println("完成时间：" + completeVO.getFinishTime());
        System.out.println("服务时长：" + completeVO.getServiceDuration());

        // 1. 验证订单是否存在且状态是否正确
        OrderInfo orderInfo = lambdaQuery()
            .eq(OrderInfo::getOrderNo, completeVO.getOrderNo())
            .one();

        if (orderInfo == null) {
            System.out.println("未找到订单信息，订单号: " + completeVO.getOrderNo());
            return new Result(400, "订单不存在", null);
        }

        System.out.println("查询到的订单信息：");
        System.out.println("订单状态：" + orderInfo.getOrderStatus());

        if (orderInfo.getOrderStatus() != 2) { // 2表示服务中状态
            return new Result(400, "订单状态不正确，只有服务中的订单才能完成服务", null);
        }

        // 2. 处理过程照片
        String processImagesStr = null;
        if (completeVO.getProcessImages() != null && !completeVO.getProcessImages().isEmpty()) {
            processImagesStr = String.join(",", completeVO.getProcessImages());
        }

        // 3. 更新订单状态
        int updated = orderInfoMapper.updateOrderStatusToComplete(
            completeVO.getOrderNo(),
            completeVO.getFinishTime(),
            completeVO.getSignInTime(),
            processImagesStr
        );

        if (updated <= 0) {
            return new Result(500, "更新订单状态失败", null);
        }

        // 4. 保存耗材使用记录
        if (completeVO.getMaterialUsages() != null && !completeVO.getMaterialUsages().isEmpty()) {
            for (ServiceCompleteVO.MaterialUsageDTO usage : completeVO.getMaterialUsages()) {
                OrderMaterial orderMaterial = new OrderMaterial();
                orderMaterial.setOrderId(orderInfo.getId().intValue()); // 转换为Integer
                orderMaterial.setMaterialId(usage.getMaterialId().intValue());
                orderMaterial.setQuantity(usage.getQuantity());
                orderMaterialMapper.insert(orderMaterial);
            }
        }
        //5.消息推送
        orderInfo.setMessages(orderInfo.getProjectId() +"任务已完成");
        return new Result(200, "服务完成确认成功", null);
    }




}



